package com.toilet.easyvideo.util;

import cn.hutool.core.util.ObjectUtil;
import com.toilet.easyvideo.security.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 用户工具类
 */
@Slf4j
public class SecurityUtils {
    /**
     * 获取用户ID
     */
    public static Long getUserId() {
        try {
            LoginUser loginUser = (LoginUser) getAuthentication().getPrincipal();
            if (ObjectUtil.isNotEmpty(loginUser)) {
                return loginUser.getSysUser().getId();
            } else {
                log.info("未能成功获取到用户信息");
                return null;
            }
        } catch (Exception e) {
            log.info("未能成功获取到用户信息,进行了捕获异常", e);
            return null;
        }
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }
}
